/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.common.exception;

import com.xr.common.axios.AxiosEnum;
import com.xr.common.axios.AxiosResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 自定义全局异常处理器
 */
@RestControllerAdvice
public class MyGlobalExceptionHandler {

	/**
	 * 处理系统未知异常
	 */
	@ExceptionHandler(Exception.class)
	public AxiosResult handle(Exception e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理运行时发生的或主动抛出的其他自定义异常（继承于RuntimeException）
	 */
	@ExceptionHandler(MyCustomException.class)
	public AxiosResult handle(MyCustomException e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理字段值重复(违背唯一约束条件)的SQL异常
	 */
	@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
	public AxiosResult handle(SQLIntegrityConstraintViolationException e) {
		e.printStackTrace();
		if (e.getMessage().contains("Duplicate entry")) {
			return AxiosResult.error(AxiosEnum.UNIQUE_ERROR);
		}
		return AxiosResult.error(AxiosEnum.UNKNOWN_ERROR);
	}

	/**
	 * 处理空指针异常
	 */
	@ExceptionHandler(NullPointerException.class)
	public AxiosResult handle(NullPointerException e) {
		e.printStackTrace();
		return AxiosResult.error(AxiosEnum.NULL_POINTER_ERROR);
	}

}
